package com.situ.day20;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import org.junit.Test;
import org.omg.CORBA.COMM_FAILURE;

import com.situ.day17.JDBCUtil;

public class TransactionDemo {
	@Test
	public void transactionDemo() {
		Connection connection = null;
		PreparedStatement preparedStatement = null;
		String sql1 = "UPDATE account SET money=money-1000 WHERE NAME='张三';";
		String sql2 = "UPDATE account SET money=money+1000 WHERE NAME='李四';";
		
		try {
			connection = JDBCUtil.getConnection();
			//默认是true，遇到executeUpdate自动提交更改数据库，而我们
			//希望开启事物，直到遇到commit()才去真正的提交到数据库
			connection.setAutoCommit(false);
			preparedStatement = connection.prepareStatement(sql1);
			preparedStatement.executeUpdate();
			int i = 3 / 0;
			preparedStatement = connection.prepareStatement(sql2);
			preparedStatement.executeUpdate();
			connection.commit();//手动提交
		} catch (SQLException e) {
			e.printStackTrace();
			try {
				connection.rollback();
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
		} finally {
			JDBCUtil.close(connection, preparedStatement, null);
		}
	}

}
